package com.xp.tinyurl.service.thirdprovider.impl;

import com.xp.tinyurl.service.thirdprovider.enums.AeinkChannelEnum;
import com.xp.tinyurl.service.thirdprovider.vo.AeURLConvertResult;
import com.xp.tinyurl.service.thirdprovider.ShorterUrlService;
import com.xp.tinyurl.common.utils.OkHttp3Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class AeinkShorterUrlService implements ShorterUrlService {
    private static final Logger logger = LoggerFactory.getLogger(UomgShorterUrlService.class);

    private static final String AEINK_SHORT_URL_API_URL = "http://tools.aeink.com/tools/dwz/urldwz.php";

    @Override
    public String shorter(String longUrl) {
        String shortUrl = null;
        Map<String, String> paramMap = new HashMap<>(2);
        paramMap.put("api", AeinkChannelEnum.values()[new Random().nextInt(3)].getName());
        paramMap.put("longurl", longUrl);
        String result = null;
        try {
            result = OkHttp3Utils.get(AEINK_SHORT_URL_API_URL, paramMap);
            AeURLConvertResult aeResult = JSON.parseObject(result, new TypeReference<AeURLConvertResult>() {
            });
            if (aeResult != null) {
                shortUrl = aeResult.getAe_url();
                logger.info("Aeink short url: {}", shortUrl);
            }
        } catch (Exception e) {
            logger.error(result);
        }
        return shortUrl;
    }

}
